	<?php
	defined('BASEPATH') OR exit('No direct script access allowed');

	class Images extends CI_Controller {

		// protected $dictArray = array();
		public function __construct()
    {
      parent::__construct();

      $this->config->load();
      $this->load->helper('url_helper');
      $this->load->database();
      $this->load->model('images_model');
    }

    //for ads
    public function add(){
      if (!isset($_SESSION['username']))
      {
          redirect('user/login');
      }


      $this->load->helper('form');
      $this->load->library('form_validation');
      $this->form_validation->set_rules('title', 'title', 'required');
             
    
      $data['title'] = '添加图片';

      
      if ($this->form_validation->run() === FALSE)
      {
     
          $this->load->view('templates/header', $data);
          $this->load->view('imagesadd');
          $this->load->view('templates/footer');
          
      }
      else
      {
          $imageUrl = $this->do_upload();
           // echo  $imageUrl;
          $this->images_model->add($imageUrl);
          redirect('images/index');
      }

    }

     public function do_upload()
      {
        $config['upload_path']      = './uploads/';
        $config['allowed_types']    = 'gif|jpg|png|jpeg';
        $config['max_size']     = 8000;
        $config['max_width']        = 4096;
        $config['max_height']       = 2048;

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload('image'))
        {
            $error = array('error' => $this->upload->display_errors());
            echo  $error['error'];

            // $this->load->view('templates/header', $error);
            // $this->load->view('ads');
            // $this->load->view('templates/footer');
            // exit;
        }

        $url = "";
        $filename = $this->upload->data('file_name');
        if (strlen($filename) > 0){
             $url = $this->config->item('base_url')."uploads/".$filename;
        }
    
       
       return $url;
    }

    public function delete($id)
    {
        if (!isset($_SESSION['username'])) {  
            redirect('user/login');  ;  
        }  
        
        // $data['title'] = '删除用户';
        
        if ($id > 0) {
            $this->images_model->delete($id);
        }
   
        redirect('images/index');

    }

    public function index(){
      if (!isset($_SESSION['username'])) {  
          redirect('user/login');  ;  
       }  
  
      date_default_timezone_set("PRC");
      $data['list'] = $this->images_model->getAll();
          
      $this->load->view('templates/header', $data);
      $this->load->view('images', $data);
      $this->load->view('templates/footer');
    }
    

    
  }
